﻿using S7CommPlusDriver.ClientApi;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace S7CommPlusDriverCore.Extension
{
    public class TagsManager
    {

        protected readonly List<TagInstanceManager> _tagInstanceManagers;

        /// <summary>
        /// 需要读取的所有标签集合
        /// </summary>
        public List<PlcTag> ReadPlcTags { get; }

        /// <summary>
        /// 需要批量写入的标签集合，需要加锁
        /// </summary>
        public List<PlcTag> WritePlcTags { get; }

        /// <summary>
        /// 标签缓存
        /// </summary>
        public List<PlcTag> TempPlcTags { get; }

        public TagsManager()
        {
            _tagInstanceManagers = new List<TagInstanceManager>();
            ReadPlcTags = new List<PlcTag>();
            WritePlcTags = new List<PlcTag>();
            TempPlcTags = new List<PlcTag>();
        }

        /// <summary>
        /// 利用反射获取特性标记的标签值
        /// </summary>
        /// <param name="tagBase"></param>
        public void InitInstance(ITagAware tagBase)
        {
            var typeInfo = tagBase.GetType().GetTypeInfo();

            foreach (var propertyInfo in typeInfo.DeclaredProperties)
            {
                var monitoredItemAttribute = propertyInfo.GetCustomAttribute<MonitoredItemAttribute>();

                if (monitoredItemAttribute is null)
                {
                    continue;
                }
                else
                {
                    if (string.IsNullOrEmpty(monitoredItemAttribute.TagName))
                    {
                        continue;
                    }
                    else
                    {
                        if (_tagInstanceManagers.FirstOrDefault(x => x.Instance.Equals(tagBase) && x.Tag == monitoredItemAttribute.TagName) is null)
                        {
                            _tagInstanceManagers.Add(new TagInstanceManager() { Instance = tagBase, PropertyInfo = propertyInfo, Tag = monitoredItemAttribute.TagName });

                            var plcTag = TempPlcTags.FirstOrDefault(x => x.Name == monitoredItemAttribute.TagName);

                            if (plcTag is not null)
                            {
                                Apply(plcTag);
                            }
                        }
                    }
                }
            }
        }

        public void AddTag(PlcTag tag)
        {
            TempPlcTags.Add(tag);
        }

        public void RemoveTag(PlcTag tag)
        {
            TempPlcTags.Remove(tag);
        }

        public void Apply(PlcTag plcTag)
        {

            ReadPlcTags.Add(plcTag);

            plcTag.TagChanged += TagsManager_TagChanged;

            //ReadPlcTags.Clear();

            //TempPlcTags.ForEach((plcTag) =>
            //{
            //    ReadPlcTags.Add(plcTag);
            //    plcTag.TagChanged += TagsManager_TagChanged;

            //});
        }

        #region Private Method

        /// <summary>
        /// 尝试获取绑定该标签的所有实例
        /// </summary>
        /// <param name="tag">标签</param>
        /// <param name="tagInstanceManagers">所有实例</param>
        /// <returns></returns>
        private bool TryGetInstanceByTag(string tag, out IEnumerable<TagInstanceManager> tagInstanceManagers)
        {
            tagInstanceManagers = null;
            var result = _tagInstanceManagers.Where(x => x.Tag == tag);
            if (result.Any())
            {
                tagInstanceManagers = result;
                return true;
            }
            return false;
        }

        /// <summary>
        /// 多个实例，多个属性，拿到那个实例那个属性进行通知
        /// </summary>
        /// <param name="plcTag"></param>
        private void TagsManager_TagChanged(PlcTag plcTag)
        {
            if (!TryGetInstanceByTag(plcTag.Name, out var tagInstanceManagers)) return;

            switch (plcTag)
            {
                case PlcTagBool plcTagBool:

                    foreach (var tagInstance in tagInstanceManagers)
                    {
                        if (tagInstance.PropertyInfo.PropertyType == typeof(bool))
                        {
                            tagInstance.PropertyInfo.SetValue(tagInstance.Instance, plcTagBool.Value);
                        }
                    }

                    break;

                case PlcTagByte plcTagByte:

                    foreach (var tagInstance in tagInstanceManagers)
                    {
                        if (tagInstance.PropertyInfo.PropertyType == typeof(byte))
                        {
                            tagInstance.PropertyInfo.SetValue(tagInstance.Instance, plcTagByte.Value);
                        }
                    }

                    break;

                case PlcTagInt plcTagInt:

                    foreach (var tagInstance in tagInstanceManagers)
                    {
                        if (tagInstance.PropertyInfo.PropertyType == typeof(short))
                        {
                            tagInstance.PropertyInfo.SetValue(tagInstance.Instance, plcTagInt.Value);
                        }
                    }

                    break;
                default: break;

            }
        }
        #endregion

    }

    public class TagTest : ITagAware
    {
        public TagTest(TagsManager tagsManager)
        {
            TagsManager = tagsManager;
        }

        private bool myVar;

        [MonitoredItem("DB_Binary.Bool_True")]
        public bool MyProperty
        {
            get { return myVar; }
            set { myVar = value; }
        }

        public TagsManager TagsManager { get; set; }


        public void Write<T>(string name, T value)
        {
            var monitoredItemAttribute = this.GetType().GetProperty(name).GetCustomAttribute<MonitoredItemAttribute>();

            var plcTag = TagsManager.TempPlcTags.FirstOrDefault(x => x.Name == monitoredItemAttribute.TagName);

            var tempTag = Helper.CreatePlcTag(plcTag.Name, plcTag.Address, plcTag.Datatype);

            tempTag.SetValue(value);

            TagsManager.WritePlcTags.Add(tempTag);
        }
    }
}
